<?php


namespace App\Http\Controllers;


use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Laravel\Passport\Client;
use Laravel\Passport\Token;
use Spatie\RouteAttributes\Attributes\Any;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;

Class PassportController extends BaseController
{
    /**
     * 个人访问客户端 生成 个人访问令牌
     * 创建个人访问令牌 会在 oauth_access_tokens 生成一条记录
     * 1.生成个人访问令牌 http://lar.loc/dispatch?mid=auth&ctl=passport
     * 2.利用访问令牌 可以通 过auth:api 登录校验
     *   模拟令牌访问 http://lar.loc/dispatch?mid=auth&ctl=passport
     */
    public function personal()
    {
        $user = User::find(1);

        // 创建令牌 会在 oauth_access_tokens 生成一条记录
        $token = $user->createToken('Token Name')->accessToken;
        return $token;
    }

    /**
     * 解析令牌，个人访问令牌和 客户凭证授予令牌 都可以解析
     */
    public function parseToken()
    {
        $accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiNGJhYjUyNzVjMmJhMmYwZTUzMjI4MTNjODAwOTVhZjUyMjU2MGJlYmY4NmJlNDhiNjczOTJjNjgyYTQyNWM0NDVmMDNhYTQ4ZGU0ZmI2Y2YiLCJpYXQiOjE3NTE4Nzc5NTcuOTIwNTA3LCJuYmYiOjE3NTE4Nzc5NTcuOTIwNTEsImV4cCI6MTc4MzQxMzk1Ny44ODY0Nywic3ViIjoiIiwic2NvcGVzIjpbIioiXX0.BiANLfhz9zEzFlfal1ADDIr2unpVs0OKS08OpJLC--ldwIc5cza_PauKRDVoG8WyjBVWqRWUPsVn7m2ujgIGIJ6mf1fwwcw7rYMCsXHZw7ZbdBzxkEuZSSs-3h8FvobzbKnNFeIP0nuprGnNKy2TVO0RuEOigOuONcJDo8_UaatTiWwKETr597musiwPi_D4vhWxpPgkr4mBpGYjbf6KX9ZqtP3WC-OJKB_9zKmIN0vcQA2C8dw3pkVmUU-Jdd3uyGVtQrjCFfy0z0MJGAukbFz-VFadkFeHTmGGzxLyncFdPK45lKpBqA7fr0CjF5WD-X-HU5o6R-cZ1InKG6tCda0lejHK6DL5Uz5ZLHIecXs4lpWUCuxlEO85UAVTbHST7FuQVwbghz3Fi8RAdAkC5fZQMHG4tQHDkYLxe_7ksdN8QJJ3__mN4Yo1noUHb1C02eRYN5634VXYNrPPZK9GtOOAZ7XMX1uL-zaGOKo_mjN-DeNB3NqZCJGSjDjtjz38EPnofkG57TO4pevj2E0CjNQj5H0Uay-25gkGmKdwOBdQZP0Td_spRnGglhbdk-ED8iijnP1VPt-eaZFf9-l8y0tynTXSPIHCrJUvWQI9y7dvyHpYvHi8aZyOwXi4_Kut9FgCyOF6UZgGlaXgiXByvuU0SqbpoW0SO5YwW9oyODY';
        $token =  base64_decode($accessToken);  //这个JWT 是非标准的,无法直接解析


        // 2. 初始化 JWT 配置
        $jwtConfig = Configuration::forAsymmetricSigner(
            new Sha256(),
            InMemory::file(storage_path('oauth-private.key')), // 私钥路径
            InMemory::file(storage_path('oauth-public.key'))   // 公钥路径
        );

        // 3. 解析令牌
        $token = $jwtConfig->parser()->parse($accessToken);

        // 4. 获取令牌数据
        $data = $token->claims()->all(); // 返回所有声明（Payload）

        return $data;
    }

    /**
     * 模拟api token 校验
     * 个人访问令牌 和 用户账户密码生成的令牌 都可以校验
     */
    public function auth()
    {
        $accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiOGIxMmU4NGVlYmVlNjU5OWI5ZDg0MzM0YmE1NGExNGM2ZjEyZTI1MmQ1MjEzYjgzZjk4YzIwMTFkNzM1NDcxNzk1MmE1YzQ4ZGRmNWZkOWIiLCJpYXQiOjE3NTE4ODE3NzIuNDg3OSwibmJmIjoxNzUxODgxNzcyLjQ4NzkwMiwiZXhwIjoxNzgzNDE3NzcyLjQzNjYzLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.b2OgpkT0FPohDZG0RMCX2tH2K-6TePAefllceAmborEQpp6qaY9kVOuH0zjH5iNK_KyUXP_LcQmTleKlqLlGNjGrml1uPFj4eQw6vhtby_KTPgJWIGP9OT4s3csbc0nM-n4V1bgljUyyEpP2wPyW23LvmjDHTKlUf37CXdlQH2yqR-EYc_gjxWbCRrMgr04LcfYnoAwv4PBK2W_i3T1YRkAYQn64T0tBM3Monbb0-HJY9xL-PdqEjzYsA4tQJpaqcEyO8xudvwWK_7LSW-rjfYUGrk--2BtoQoOtfW4bTzssa1eBP2UiYADH4P12u8AsOPPXRokB7bqpI-0T6b_FKBP0OH7M34LAvxTZ7Dgve4NyAL9yKg30D4uzxo9J9y6u0cqftOQa-Z0iWYz5w5Ha8a0A5NKrMj84_SXZ5gTA0d4PhmF42X2Bis58Bg1ZaG-3tmP7aJDaAZ50-pQqj4pc_KvsWMegrtKSh5WlxbJj0WPh6p4vAQkeHwK4nZTbCJGFxFehCXvvIzgKIu6RsXueNAYDDHW0YnPucim8rQwoI7ekFIeglTJOlbMCGZUU-i4xMCtFxK6ThhjIF_lBbzWQA6VRew_Y96n_8zlehVmi6yxP7P_1w8NKCblSy6OOVj7dZwh2v9LK3akzKUV2WfaPvQn4MDCrMCg-bAOX86RrjLI';
        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$accessToken,
        ])->get('http://nginx/passport/user');  //PHP容器访问web服务,只有访问nginx了

        return $response->json();
    }

    /**
     * 获取当前登录用户
     */
    #[Any('passport/user', middleware: ['api','auth:api'])]
    public function user(request $request)
    {
        $user = Auth::user();
        return $user ?? 'no user';
    }

    # Password 令牌 ------
    /**
     * 根据用户名和密码 请求 oauth/token 生成令牌
     * 生成 access_token 插入 一条记录到 oauth_access_tokens
     * 生成 refresh_token 插入一条记录到 oauth_refresh_tokens
     */
    public function createPassToken()
    {
        $client = Client::query()->where('id',2)->first();
        $response = Http::asForm()->post('http://nginx/oauth/token', [
            'grant_type' => 'password',
            'client_id' =>  $client->id,
            'client_secret' => $client->secret,
            'username' => '1107985549@qq.com',
            'password' => '12345678',
            'scope' => '',
        ]);

        return $response->json();
    }

    # Credentials令牌 ------
    /**
     * 客户凭证客户端 获取授权令牌 client
     * 生成 机器授权码 请求服务器接口 oauth/token
     * 创建机器授权码令牌 会在 oauth_access_tokens 生成一条记录
     * 创建机器授权码令牌 使用的client 可以是 任意的client类型，不校验
     */
    public function createCredentials()
    {
        $client = Client::query()->where('id',1)->first();
        $response = Http::asForm()->post('http://nginx/oauth/token', [
            'grant_type' => 'client_credentials',
            'client_id' => $client->id,
            'client_secret' => $client->secret,
            'scope' => '*',
        ]);

        return $response->json()['access_token'];
    }

    public function credentialsAuth()
    {
        $accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZTcxY2MzNjU2ZTgyY2VjY2ZjNTA0MGUzZWMzOTYzNTJkYWM0OTNlZDAyMTdiNDJmNTlmZjZlNGU2ZWU4ZmIxOTE0NDdmMzhlYmQ5N2IyMmEiLCJpYXQiOjE3NTE4Nzg5MDQuMzA5NywibmJmIjoxNzUxODc4OTA0LjMwOTcwMywiZXhwIjoxNzgzNDE0OTA0LjI4NTA4MSwic3ViIjoiIiwic2NvcGVzIjpbIioiXX0.o-1gQgC9YiTiKbjZUhqOblk_f0SjZBv89Nwhr2jg84O5gURFuTRgztz065x1_mEI_92crux4RpeQWpeVlAybESZ8w3L-UK1_mELRn0osS5cb1wI7V87x9xYu-enWiKoIIvxAlkDZ2otUqWTYDjPPkBYRcILpuM-fPIcZva2NZ791gZLDfHplZGPefS9OrpTTQNv2N_H7e_4tK9ZWRBZJGutYbYRXxR2iPYb1pqk2FURCuUu5suWI6Q6lPaDt1WHrg_MHSIQ2CV6awTj8X36YXUcHhhwRwSrOKczBcBVUXyrNSc14Pr6jOwRmIggxFPR_jWqDmTIUfk_EAtvKLO42OKQaLinbxVXpi9poaFA3pia-pM4jqAA87jvXBCpYKC5Bjlzo5qVshWQOtFjR0rbpn9DNTVz-qzuJi6_ClFCnH-GUXxxRDQtoFyr0254cg1kmA-27JewNiXklEEklaTARwTv-o4uREjw_RFxKnlJhW08wANivduR2BWe6zCOG6jXjJR3Km6vmVxGkvrGCSIMkOdvDJ0hfiiuX8HFaGWRN35LbYFOErGZt9w-9UYvEZzztmJleKpXkJVXIh1bF7Z4YbrtNwyVBF3HNa7N0eW0WFoTyuQACZ4YGVwxfs70i4gZe9YslZj8JaVwSB0WQ7AWRiKYqnMrSlHaV3lOnMWIlgcQ';
        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$accessToken,
        ])->get('http://nginx/passport/credentialsCheck');  //PHP容器访问web服务,只有访问nginx了
        return $response->json();
    }

    /**
     * 校验credentials 令牌
     */
    #[Any('passport/credentialsCheck', middleware: ['client'])]
    public function credentialsCheck(request $request)
    {
        $user = User::find(1); //
        return $user ?? 'no user';
    }
}
